﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ProtoBuf;
using System.IO;


public partial class ProtoBuf序列化aspx : System.Web.UI.Page
{
    /// <summary>
    /// 序列化对像
    /// </summary>
    HistorySerialize ser = new HistorySerialize();
    protected void Page_Load(object sender, EventArgs e)
    {

        List<testT> list = new List<testT>();
        System.Linq.Enumerable.Range(1, 200).ToList().ForEach((o) =>
                                                                  {
                                                                      list.Add(new testT() { strZ = Guid.NewGuid().ToString() });
                                                                  });

        ser.Serialize(list.ToArray(),"aa");
        ser.Deserialize("aa");

    }
}

/// <summary>
/// 测试类
/// </summary>
[ProtoBuf.ProtoContract]
public class testT
{
    [ProtoMember(1)]
    public string strZ { get; set; }
}

/// <summary>
/// 历史数据序列化
/// </summary>
[Serializable]
internal class HistorySerialize
{

    /// <summary>
    /// 序列化数据到硬盘
    /// </summary>
    /// <param name="dt">历史数据集合对像</param>
    /// <param name="name">名称</param>
    public void Serialize(testT[] dt, string name)
    {
        using (FileStream fileStream = new FileStream(GetErrorPath(name), FileMode.Create))
        {
            //序列化数据
            Serializer.Serialize(fileStream, dt);
            fileStream.Close();
        }

    }
    /// <summary>
    /// 反序列化 
    /// </summary>
    /// <param name="fileName"></param>
    /// <returns></returns>
    public testT[] Deserialize(string fileName)
    {
        testT[] dt = null;

        using (FileStream fileStream = new FileStream(GetErrorPath(fileName), FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            dt = Serializer.Deserialize<testT[]>(fileStream);
            fileStream.Close();
        }

        return dt;
    }


    private string GetErrorPath(string name)
    {
        var path =AppDomain.CurrentDomain.BaseDirectory;
        path = path + @"\ED\";
        if (!Directory.Exists(path))
        {
            lock (this)
            {
                if (!Directory.Exists(path))
                    Directory.CreateDirectory(path);
            }
        }
        path = path + name +".err";
        return path;
    }
}